package org.example.algorithm.binarytree;

import org.example.algorithm.TreeNode;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;

/**
 * 翻转二叉树:
 * 给定一棵二叉树的根节点 root，请左右翻转这棵二叉树，并返回其根节点。
 */
public class MirrorTreeSolution {
    public static void main(String[] args) {

    }

    //递归
    public TreeNode mirrorTree(TreeNode root) {
        if (root != null) {
            TreeNode temp = root.left;
            root.left = mirrorTree(root.right);
            root.right = mirrorTree(temp);
        }
        return root;
    }

    //层序遍历方式翻转
    public TreeNode invertTreeByQueue(TreeNode root) {
        if (root != null) {
            Queue<TreeNode> nodeQueue = new ArrayDeque<>();
            nodeQueue.offer(root);
            while (!nodeQueue.isEmpty()) {
                TreeNode node = nodeQueue.poll();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                if (node.left != null) {
                    nodeQueue.offer(node.left);
                }
                if (node.right != null) {
                    nodeQueue.offer(node.right);
                }
            }
        }
        return root;
    }

    /**
     * 深度优先遍历的方式反转
     */
    private TreeNode invertTreeByStack(TreeNode root) {
        if (root != null) {
            Stack<TreeNode> nodeStack = new Stack<>();
            nodeStack.push(root);
            while (!nodeStack.isEmpty()) {
                TreeNode node = nodeStack.pop();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                if (node.left != null) {
                    nodeStack.push(node.left);
                }
                if (node.right != null) {
                    nodeStack.push(node.right);
                }
            }
        }
        return root;
    }
}
